package app;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.RowSorterEvent;
import javax.swing.event.RowSorterListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import KUtilities.KSpringOld;
import KUtilities.KTextField;

public class ContactsPanel extends JPanel {
	private static final long serialVersionUID = 1L;
	private PrintWriter writer=null;
	private JTable contactsTable;
	private KTextField numbers;
	private DefaultTableModel contacts;
	private File contactsFile;
	
	public ContactsPanel(SMSPanel smsPanel){
		numbers=smsPanel.getNumbersField();
		final JScrollPane contactsPane;
		final String titles[]={"Name","Phone Number"};
		setOpaque(false);
		contacts=new DefaultTableModel();
		contacts.setColumnCount(2);
		contacts.setColumnIdentifiers(titles);
		contactsFile=new File("data"+File.separator+"Contacts.txt");
		File oldContactsFile=new File("Contacts.txt");
		File f=new File("data");
		if(!f.exists())
			f.mkdir();
		if(oldContactsFile.exists()){
			oldContactsFile.renameTo(contactsFile);
		}
		if(contactsFile.exists()){
			try{
				BufferedReader br=new BufferedReader(new FileReader(contactsFile));
				String temp=br.readLine();
				while(temp!=null){
					String temp2[]=temp.split("--");
					contacts.addRow(temp2);
					temp=br.readLine();
				}
			}catch(Exception e){}
		}
		contacts.setRowCount(contacts.getRowCount()+1);
		
		contactsTable=new JTable(contacts);
		contactsTable.setAutoCreateRowSorter(true);
		contactsTable.setAutoscrolls(true);
		contactsTable.setFillsViewportHeight(true);
		contactsPane=new JScrollPane(contactsTable);
		
		@SuppressWarnings("unchecked")
		RowSorter<DefaultTableModel> sorter=(RowSorter<DefaultTableModel>) contactsTable.getRowSorter();
		sorter.addRowSorterListener(new RowSorterListener(){
			public void sorterChanged(RowSorterEvent re) {
				saveContacts();
			}
		});
	
		KSpringOld contactsSpring=new KSpringOld(this);
		contactsSpring.add(contactsPane);
		contactsSpring.setHGap(5, this,contactsPane,this);
		contactsSpring.setVGap(5, this,contactsPane,this);
		contactsSpring.setWidth(contactsPane, contactsSpring.getWidth(contactsPane).getValue()-100);
		
		Thread t=new Thread(){
			public void run(){
				try {
					HashMap<String,String> contactsMap=new HashMap<String,String>();
					for(int i=0;i<contacts.getRowCount();i++){
						Object name=contactsTable.getValueAt(i, 0);
						Object phone=contactsTable.getValueAt(i, 1);
						if(name!=null && phone!=null)
							contactsMap.put(name.toString(), phone.toString());
					}
					numbers.enableAutoComplete(contactsMap,true);
					numbers.setAutoCompleteSeperator(";");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
		
		
		contacts.addTableModelListener(new TableModelListener(){
			public void tableChanged(TableModelEvent te) {
				if(te.getType()==TableModelEvent.UPDATE){
					if(te.getLastRow()>=contacts.getRowCount()-1){
						contacts.setRowCount(contacts.getRowCount()+1);
					}
				}
				saveContacts();
			}
		});
		
		contactsTable.addKeyListener(new KeyAdapter(){
			public void keyTyped(KeyEvent ke){
				if(ke.getKeyChar()==KeyEvent.VK_DELETE){
					int num[]=contactsTable.getSelectedRows();
					for(int i=num.length-1;i>=0;i--){
						num[i]=contactsTable.convertRowIndexToModel(num[i]);
						contacts.removeRow(num[i]);
					}
					contacts.fireTableDataChanged();
				}
			}
		});
		
		contactsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent le) {
				int num[]=contactsTable.getSelectedRows();
				String numText="";
				for(int i=0;i<num.length;i++){
					num[i]=contactsTable.convertRowIndexToModel(num[i]);
					String temp=(String) contacts.getValueAt(num[i], 1);
					if(temp!=null)
						numText+=temp+";";
				}
				numbers.setText(numText);
				contactsTable.requestFocus();
			}
		});
	}

	protected void saveContacts() {
		try {
			writer=new PrintWriter(new FileWriter(contactsFile));
			for(int i=0;i<contactsTable.getRowCount();i++){
				String name=(String) contactsTable.getValueAt(i,0);
				String num=(String) contactsTable.getValueAt(i,1);
				if(name!=null && num!=null)
				writer.println(name+"--"+num);
			}
		} catch (Exception e) {
		}finally{
			if(writer!=null)
				writer.close();
		}
	}
}
